from django.shortcuts import render

# Create your views here.
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.viewsets import GenericViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

import logging
from . import constants
from .models import Users, Address
from .userSerializers import CreateUserSerializer, EmaileSerializer, UserAddressSerializer, AddressTitleSerializer
from users.utils import check_verif_email_token
from carts.utils import merge_cart_cookie_to_redis


class Usernamecount(APIView):
    """
    获取用户数量
    """

    def get(self, request, username):
        """
        获取用户指定
        :return:
        """
        try:
            count = Users.objects.filter(username=username).count()
        except Exception as e:
            logging.error(e)
            return Response("username%s" % e)

        data = {
            "username": username,
            "count": count
        }

        return Response(data)


class Mobilecount(APIView):
    """
    获取用户手机数量
    """

    def get(self, request, mobile):
        """
        获取指定手机
        :param request:
        :param mobile:
        :return:
        """
        try:
            count = Users.objects.filter(mobile=mobile)
        except Exception as e:
            logging.error(e)
            return Response("moble%s" % e)

        data = {
            "mobile": mobile,
            "count": count
        }

        return Response(data)


class UersView(CreateAPIView):
    """
    用户视图：新增用户
    """
    # create_serializer=CreateUserSerializer
    # 报错"UersView" 应该包含 "serializer_class" 属性, 或者重写 "get_serializer_class ()" 方法
    serializer_class = CreateUserSerializer


class UserDataView(APIView):
    """显示用户个人中心"""
    # 判断用户是否登陆如果用户未登录不能访问
    permission_classes = [IsAuthenticated]

    # get继承apiv视图方法
    def get(self, request):
        # 获取当前登陆用户[request.user 获取当前已经登陆的用户了]
        user = request.user
        # 响应数据
        return Response({
            "id": user.id,
            "username": user.username,
            "mobile": user.mobile,
            "email": user.email,
            "email_active": user.email_active
        })


class EmaileView(UpdateAPIView):
    """保存用户邮箱"""
    serializer_class = EmaileSerializer

    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    """
    邮箱验证链接
    """

    def get(self, request):

        # 获取token
        try:
            token = request.query_params.get("token")
        except Exception:
            return Response({"message": "缺少token"})

        # 校验token

        user_id = check_verif_email_token(token)

        # 判断是否为空
        if user_id is None:
            return Response({
                "message": "token无效"
            })

        # 根据id获取用户信息

        try:
            user = Users.objects.get(pk=user_id)
        except:
            return Response({"message": "无效的token"}, status=status.HTTP_400_BAD_REQUEST)

        # 更改邮箱验证状态
        user.email_active = True
        user.save()

        # 响应数据
        return Response({"message": "ok"}, status=status.HTTP_200_OK)


class AddressViewSet(ModelViewSet):
    """用户收货地址视图集"""
    # 设置权限,非登陆用户不能访问
    permission_classes = [IsAuthenticated]

    # 创建序列化器对象
    serializer_class = UserAddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    # 设置查询集
    # 查询当前用户地址
    # def get_queryset(self):
    #     return Address.objects.filter(is_deleted=False, user=self.request.user)
    #     # return self.request.user.Address.filter(is_deleted=False)

    # 序列化用户字段，调用Method list overrides method of class ListModelMixin.Do you want to find usages of the base method?
    def list(self, request, *args, **kwargs):
        # 获取用户模型
        queryset = self.get_queryset()
        # 创建序列化对象
        serializer = self.get_serializer(queryset, many=True)

        user = self.request.user
        print(user, user.default_address_id)

        return Response({
            "limit": constants.USER_ADDRESS_COUNTS_LIMIT,
            "default_address_id": user.default_address_id,
            "addresses": serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 检查用户地址保存不能超过上限
        count = request.user.addresses.count()

        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除的
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


        # # put /addresses/pk/status/

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

        # put /addresses/pk/title/
        # 需要请求体参数 title

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# 修改ｊｗｔ中的認證視圖，重寫ｐｏｓｔ提交中的方法來添加合並邏輯

class UserAuthorizeView(ObtainJSONWebToken):
    """
    用戶認證，在原有的ｊｗｔ登陸功能中，添加合並購物車功能
    JSONWebTokenAPIView
    """

    def post(self, request, *args, **kwargs):
        """
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 調用父類的方法，獲取ｄｒｆ　ｊｗｔ中的擴展默認的認證用戶處理結果
        response = super().post(request, *args, **kwargs)
        # 仿照ｄｒｆ　ｊｗｔ中的對於用戶登陸的認證方式，判斷用戶是否認證登陸陳功
        # 如果用戶登陸成功則合並購物車
        # 獲取當前登陸用戶

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            # user = serial
            # izer.validated_data.get('user')
            # 補充合並購物車代碼
            response = check_verif_email_token(request, user, response)

        return response
